package com.zzj.service.impl;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzj.entity.User;
import com.zzj.mapper.UserMapper;
import com.zzj.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzj.utils.JWTUtil;
import com.zzj.utils.RSAUtil;
import com.zzj.utils.Utils;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zzj
 * @since 2023-05-12
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public User findUserByUsername(String username, String password) throws Exception {

        password = RSAUtil.decrypted(password);
        password = SecureUtil.md5(password);

        return this.getOne(Wrappers.<User>lambdaQuery()
                        .eq(User::getPassword, password)
                        .eq(User::getUsername, username),
                false);
    }

    @Override
    public User findUserByUsername(String username) {
        return this.getOne(Wrappers.<User>lambdaQuery()
                        .eq(User::getUsername, username),
                false);
    }

    @Override
    public User findUserByOpenId(String openId) {
        return this.getOne(Wrappers.<User>lambdaQuery()
                        .eq(User::getOpenId, openId),
                false);
    }

    @Override
    public User updateIpAddress(int id, String ip, String address) {
        this.lambdaUpdate().eq(User::getId, id)
                .set(User::getLoginIp, ip)
                .set(User::getLoginAddress, address)
                .set(User::getLoginTime, Utils.getNowString()).update();

        return this.getById(id);
    }

    @Override
    public void updateLoginTime(String username) {
        this.lambdaUpdate().eq(User::getUsername, username)
                .set(User::getLoginTime, Utils.getNowString()).update();
    }

    @Override
    public User createUser(String username, String password, int status) throws Exception {
        password = RSAUtil.decrypted(password);
        password = SecureUtil.md5(password);

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setStatus(55);
        this.save(user);
        return user;
    }


}
